import qs from 'qs'
import { tokenStorage } from '@/utils/storage'
export default function ({ store, $axios, redirect }) {
  const accessToken = tokenStorage.get()
  if (accessToken) {
    store.commit('auth/SET_USER_TOKEN', accessToken)
  }
  $axios.onRequest((config) => {
    if (config.data instanceof FormData) {
      config.data.append('access_token', store.state.auth.userToken)
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      const params = {
        chain_network: 'main_network',
        language: ['zh', 'tw'].includes(store.state.locale) ? 'zh_cn' : 'en_us',
        os: 'ios',
        os_ver: '13.3.1',
        soft_ver: '1.0.0',
        ...config.data
      }
      if (store.state.auth.userToken) {
        params.access_token = store.state.auth.userToken
      }
      config.data = qs.stringify(params)
    }
  })
  $axios.onResponse(({ data }) => {
    const { code } = data
    // if (code === 401) {
    //   redirect('/login')
    // }
    if (code !== 200) {
      return Promise.reject(data)
    }
  })

  $axios.onError((error) => {
    const { code } = error
    if (code === 401) {
      tokenStorage.set('')
    }
  })
}
